package com.blog.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.blog.common.Result;
import com.blog.dto.LoginDto;
import com.blog.pojo.Admin;
import com.blog.service.AdminService;
import com.blog.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 管理员相关
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    /**
     * 管理员登陆
     * @param admin 管理员对象
     * @return Result<LoginDto>
     */
    @PostMapping("/login")
    public Result<LoginDto> adminLogin(@RequestBody Admin admin){
        String adminAccount = admin.getAdminAccount();
        if (!"".equals(adminAccount)&&adminAccount!=null){
            LambdaQueryWrapper<Admin> adminLambdaQueryWrapper = new LambdaQueryWrapper<>();
            adminLambdaQueryWrapper.eq(Admin::getAdminAccount,adminAccount);
            Admin a = adminService.getOne(adminLambdaQueryWrapper);
            if (a != null){
                if (a.getAdminPassword().equals(admin.getAdminPassword())){
                    String token = JwtUtil.createToken(a);
                    LoginDto loginDto = new LoginDto();
                    loginDto.setToken(token);
                    loginDto.setUserId(a.getId());
                    loginDto.setUserAccount(a.getAdminAccount());
                    return Result.success(loginDto);
                }else {
                    return Result.error("管理员密码错误！");
                }
            }else {
                return Result.error("该管理员不存在！");
            }
        }else {
            return Result.error("管理员账号不能为空！");
        }
    }
}
